package com.masterclient.app.modules.order;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.masterclient.app.BaseActivity;
import com.eoner.common.config.Config;
import com.masterclient.app.R;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.baselib.utils.sp.SPUtils;
import com.masterclient.app.widget.FlowLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.eoner.baselibrary.utils.ScreenUtils.dp2px;

/**
 * @auther hjian
 * @date 2019/10/25.
 */
public class CommonSearchActivity extends BaseActivity {

    @BindView(R.id.vf_cancel)
    TextView vfCancel;
    @BindView(R.id.vf_edit)
    EditText vfEdit;
    @BindView(R.id.vf_search_del)
    ImageView vfSearchDel;
    @BindView(R.id.vf_search)
    FrameLayout vfSearch;
    //    @BindView(R.id.gv_search)
//    NonScrollGridView gvSearch;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.flow_history)
    FlowLayout flowHistory;

    //    private TeamGridAdapter teamGridAdapter;
    private List<String> historys;
    private Gson gson;

    private int type;
    private String search_history_key;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vf_search);
        ButterKnife.bind(this);

        type = getIntent().getIntExtra("type",0);
        switch (type){
            case 0:
                search_history_key = Config.TEAM_SEARCH_HISTORY;
                break;
            case 1:
                search_history_key = Config.INCOME_SEARCH_HISTORY;
                vfEdit.setHint("请输入订单号/手机号搜索");
                break;
            case 2:
                search_history_key = Config.ORDER_SEARCH_HISTORY;
                vfEdit.setHint("请输入订单号");
                break;
        }


        historys = new ArrayList<>();
        gson = new Gson();
//        teamGridAdapter = new TeamGridAdapter(this, historys, 1);
//        gvSearch.setAdapter(teamGridAdapter);
        getSearchHistory();
//        gvSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                startActivitryForResult(TeamSearchResultActivity.class, new String[][]{{"keyword", historys.get(position)}});
//
//            }
//        });

        vfEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                ivClear.setVisibility(vfEdit.getText().toString().length() > 0 ? View.VISIBLE : View.GONE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        vfEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String search = vfEdit.getText().toString().trim();
                    ((InputMethodManager) vfEdit.getContext().getSystemService(
                            Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                            getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    if (TextUtils.isEmpty(search)) {
                        showToast("搜索内容不能为空");
                    } else {
                        if (historys.contains(search)) {
                            historys.remove(search);
                        }
                        if (historys.size() == 10) {
                            historys.remove(0);
                        }
                        historys.add(search);
                        SPUtils.getInstance().put(search_history_key, gson.toJson(historys));
                        switch (type){
                            case 1:
//                                startActivitryForResult(IncomeCommissionSearchResultActivity.class, new String[][]{{"keyword", search}});
                                break;
                            case 2:
                                ARouter.getInstance().build(AroutePath.ORDER_SEARCH_RESULT_ACTIVITY).withString("keyword", search).navigation(CommonSearchActivity.this,100);
                                break;
                        }
                    }
                    return true;
                }
                return false;
            }
        });
    }

    @OnClick({R.id.vf_cancel, R.id.vf_search_del, R.id.iv_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.vf_cancel:
                finish();
                break;
            case R.id.vf_search_del:
                SPUtils.getInstance().put(search_history_key ,"");
                historys.clear();
                getSearchHistory();
                break;
            case R.id.iv_clear:
                vfEdit.getText().clear();
                break;
        }
    }

    private void getSearchHistory() {
        String history = SPUtils.getInstance().getString(search_history_key);
        if (TextUtils.isEmpty(history)) {
            vfSearch.setVisibility(View.GONE);
//            gvSearch.setVisibility(View.GONE);
            flowHistory.setVisibility(View.GONE);
        } else {
            vfSearch.setVisibility(View.VISIBLE);
//            gvSearch.setVisibility(View.VISIBLE);
            flowHistory.setVisibility(View.VISIBLE);
            historys = gson.fromJson(history, new TypeToken<ArrayList<String>>() {
            }.getType());

            flowHistory.removeAllViews();
            int size = historys.size();
            for(int i = (size-1);i>=0;i--){
                String s = historys.get(i);
                TextView t = (TextView) View.inflate(CommonSearchActivity.this, R.layout.item_text, null);
                t.setText(s);
                t.setTextColor(0xFF141922);
                t.setBackgroundResource(R.drawable.shape_round_f0f2f5);
                t.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        switch (type){
                            case 1:
//                                startActivitryForResult(IncomeCommissionSearchResultActivity.class, new String[][]{{"keyword", s}});
                                break;
                            case 2:
                                ARouter.getInstance().build(AroutePath.ORDER_SEARCH_RESULT_ACTIVITY).withString("keyword", s).navigation(CommonSearchActivity.this,100);
                                break;
                        }
                    }
                });
                ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                lp.setMargins(dp2px(4), 0, dp2px(4), dp2px(16));
                flowHistory.addView(t,lp);
            }
//            flowHistory.specifyLines(Integer.MAX_VALUE);
//            teamGridAdapter.setList(historys);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            getSearchHistory();
        }
    }
}
